package com.xiaoyu.tool.controller.admin;

import com.xiaoyu.tool.entity.adminUser.AdminUser;
import com.xiaoyu.tool.service.admin.AdminUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Optional;

@Controller
@RequestMapping("/admin")
public class AdminSessionController extends AdminBaseController {

    private final AdminUserService adminUserService;

    public AdminSessionController(HttpServletRequest servletRequest, AdminUserService adminUserService) {
        super(servletRequest, adminUserService);
        this.adminUserService = adminUserService;
    }

    @GetMapping("login")
    public String login(Model model) {
        model.addAttribute("login", new AdminUser());
        return "admin/sessions/login";
    }

    @GetMapping("logout")
    public String logout() {
        logoutAdminUser();
        return "redirect:/admin/login";
    }

    @PostMapping("/login")
    public String login(@Valid @ModelAttribute("login") AdminUser user, BindingResult result) {
        if(result.hasErrors()){
            return "admin/sessions/login";
        }
        Optional<AdminUser> adminUser = adminUserService.login(user);
        if (adminUser.isPresent()){
            if(adminUser.get().getStatus()){
                loginAdminUser(adminUser.get());
                return "redirect:welcome";
            }
            result.reject("errors.user.disabled");
            return "admin/sessions/login";
        }else {
            result.reject("errors.invalid.login");
            return "admin/sessions/login";
        }
    }
}
